package com.lunker.moneyrecord;

import java.util.Calendar;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider {

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		Intent intent = new Intent(context, com.lunker.moneyrecord.NewRecordActivity.class);
		intent.putExtra("oneshot", true);		
		PendingIntent pintent = PendingIntent.getActivity(
				context, 
				0, 
				intent, 
				0);
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget);
		remoteViews.setOnClickPendingIntent(R.id.appwidget, pintent);
		remoteViews.setTextViewText(R.id.txt_widgetTotal, Float.toString(getTotal(context)));
		
		if (appWidgetIds != null) {
			//Update widgets whose IDs are given.
			appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
		} else {
			//Update all widgets belong to this application.
			appWidgetManager.updateAppWidget(new ComponentName(context, this.getClass()), 
					remoteViews);
		}
	}
	
	public void notifyChange (Context context) {
		//Method to update all widgets for calling from other class.
		onUpdate(context, AppWidgetManager.getInstance(context), null);
	}
	
	private float getTotal (Context context) {
		MyDatabaseOpenHelper helper = new MyDatabaseOpenHelper(context);
		SQLiteDatabase mydb = helper.getReadableDatabase();
		Calendar cal = Calendar.getInstance();
		Cursor cr = mydb.query(
				"money_record", 
				new String[] {
						"total(amount)"
				}, 
				"year = ? and month = ?", 
				new String[] {
						Integer.toString(cal.get(Calendar.YEAR)), 
						Integer.toString(cal.get(Calendar.MONTH))
				}, 
				null, 
				null, 
				null);
		float total = 0;
		
		if (cr.moveToFirst()) {
			total = cr.getFloat(0);
		}
		
		cr.close();
		mydb.close();
		return total;
	}

}
